package service

import (
	"CodeCover/internal/log"
	"CodeCover/internal/utils"
	"path/filepath"
	"strconv"

	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
)

type GitService struct {
	prefixPath string //every git repo will be download to {prefixPath}/userID/tid
}

// prefix must be ended wit
func NewGitService(prefix string) *GitService {
	return &GitService{prefixPath: prefix}
}

func (s *GitService) LoadPath() string {
	return s.prefixPath
}

// 1. clone Git Repo to identify path
// Clone("https://gitee.com/zengyif/webserver", "master", 1235, 3458)
// will clone webserver:master into {prefixPath}/1235/3458 directory
func (s *GitService) Clone(url string, branch string, uid uint64, tid string) error {

	absDir := filepath.Join(s.prefixPath, strconv.FormatUint(uid, 10), tid, utils.RepoName(url))

	_, err := git.PlainClone(absDir, false, &git.CloneOptions{
		URL:           url,
		ReferenceName: plumbing.NewBranchReferenceName(branch),
		SingleBranch:  true,
	})
	if err != nil {
		log.Logger.Errorf("GitService:Clone, error:%v", err)
	}
	return err
}
